
import sys
import ab_error


class TryWrapper:
    def __init__(self, parent, app, function):
        self.app = app
        self.parent = parent
        self.function = function

    def __call__(self, *args, **kws):
        try:
            ret = self.function(*args, **kws)
        except:
            self.app.error('TryWrapper <%r>' % self.function)
            # FIXME: add the debug check?
            if 1:
                dialog = ab_error.ErrorDialog(self.parent, sys.exc_info())
                dialog.CenterOnScreen()
                dialog.ShowModal()
            ret = None

        return ret


class TryWrapperFactory:
    def __init__(self, parent, app):
        self.app = app
        self.parent = parent

    def __call__(self, function):
        return TryWrapper(self.parent, self.app, function)


class ExecWrapper:
    def __init__(self, parent, show_exception=False):
        self.rets = None
        self.exception = None

        self.parent = parent
        self.show_exception = show_exception

    def __call__(self, func, *args, **kws):
        self.error = None

        try:
            self.rets = func(*args, **kws)
        except:
            self.error = sys.exc_info()

        if self.error and self.show_exception:
            dialog = ab_error.ErrorDialog(self.parent, sys.exc_info())
            dialog.CenterOnScreen()
            dialog.ShowModal()

            return None
        else:
            return self.rets


class AofException(Exception):
    def __init__(self, tag, description):
        self.tag = tag
        self.description = description

        Exception.__init__(self, description)

    def __str__(self):
        return "%s: %s" % (self.tag, self.description)
